var rootPath = getRootPath();
var currentPagNo = 1;
$(function() {
	$('#usersTable').DataTable({
        "language": {
        	"lengthMenu": "每页 _MENU_ 条记录",
            "zeroRecords": " ",
            "info": "当前 _START_ 条到 _END_ 条 &nbsp;&nbsp;&nbsp;共 _TOTAL_ 条记录",
            "infoEmpty": "无记录",
            "infoFiltered": "",//(从 _MAX_ 条记录过滤)
            "search": "搜索",
            "processing": "载入中",
            "paginate": {
                "first": "首页",
                "previous": "上一页",
                "next": "下一页",
                "last": "尾页"
            }
        },
        serverSide: true,
        info: true,
        lengthChange: false,//是否允许用户改变表格每页显示的记录数
        ordering: true,//是否允许用户排序
        paging: true,//是否分页
        processing: true,
        searching: false,
        pagingType: "simple_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
        stateSave: true,//刷新时是否保存状态
        autoWidth: true,//自动计算宽度
        orderMulti: true,
        pageLength: 10,
        order: [[6,'desc']],
        fnInitComplete:function(){//创建完成回调缩略图创建
        	//$('.galpop').galpop();
        },
		"ajax" : {
			"type": "POST",
			"url": rootPath + '/user/queryUsersByInfo',
			// 默认为data，这里定义为demo
			"dataType":'json',
			"contentType": "application/json",
		    "data": function ( data ) {
		    	console.log(data)
		    	var rleId = $("#rleId").val();
		    	if(rleId) {
		    		data.columns[1].search.value = $.trim(rleId);
		    	} else {
		    		data.columns[1].search.value = "";
		    	}
		    	var info = $("#info").val();
		    	if(info) {
		    		data.columns[2].search.value = $.trim(info);
		    	} else {
		    		data.columns[2].search.value = "";		    		
		    	}
		    	var startCtsString = $("#startCts").val();
		    	if(startCtsString) {
		    		data.columns[3].search.value = $.trim(startCtsString);
		    	} else {
		    		data.columns[3].search.value = "";		    		
		    	}
		    	var endCtsString = $("#endCts").val();
		    	if(endCtsString) {
		    		data.columns[4].search.value = $.trim(endCtsString);
		    	} else {
		    		data.columns[4].search.value = "";		    		
		    	}
		    	return JSON.stringify(data);
		    },
		    error:function(){
		    	$("#refresh").click();
		    }
		},
		"columns" : [ {
			"data" : null,
			"render" : function(data, type, row, meta) {
				return "<td><input type='checkbox' value='"
					+ data.uid
					+ "' name='userCheckbox'></td>";
			},
			"name" : "checkBox",
			"orderable" : false,
			"searchable" : false,
		}, {
			"name" : "uid",
			"data" : "uid",
			"orderable" : false,
		}, {
			"name" : "uname",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.uname?data.uname:"";
			},
			"orderable" : false,
		},
		 {
			"name" : "realName",
			"data" : null,
			"render" :function(data, type, row, meta) {
				if( data.verified && data.verified=='Y'){
					return data.realName?data.realName:"";
				} else {
					return "";
				}
			},
			"orderable" : false,
		},
		{
			"name" : "phone",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.phone?data.phone:"";
			},
			"orderable" : false,
		}, {
			"name" : "email",
			"data" : null,
			"render" :function(data, type, row, meta) {
				return data.email?data.email:"";
			},
			"orderable" : false,
		}, {
			"name" : "roles",
			"data" : null,
			"render" :function(data, type, row, meta) {
				var roles = data.roles;
				var roleLength = roles.length;
				var rleName = ""
				if(roles != '' && roleLength > 0) {
					for(var j = 0;j < roleLength;j++) {
						rleName += roles[j].rleName + ",";
					}
					rleName = rleName.substring(0,rleName.length-1);
				} 
				return rleName;
			},
			"orderable" : false,
		}, {
			"name" : "cts",
			"data" : "cts",
		},{
			"data" : null,
			"render": function (data,type,row,meta) {
										var tr = "";
			//需要测试 修改！！！！！！！！！！！！！！！！！						
										tr = "<a title='编辑' href='javascript:;' onclick='user_add_edit(\"编辑用户\","
												+ "\"userEditPage?uid="
												+ data.uid
												+ "\", \"\",\"\",\"\")' style='text-decoration:none'><i class='iconfont marginLeft12'>&#xe60a;</i></a>";
//										tr += "<a title='删除' href='javascript:;' onclick='user_del(this,"
//												+ "\""
//												+ data.uid
//												+ "\")' class='ml-5' style='text-decoration:none'><i class='Hui-iconfont'>&#xe6e2;</i></a>";
										tr += "<a title='清空缓存' href='javascript:;' onclick='user_update_mts(this,"
												+ "\""
												+ data.uid
												+ "\")' class='ml-5' style='text-decoration:none'><i class='iconfont marginLeft12'>&#xe61b;</i></a>";
										tr += "<a title='添加/取消黑名单' href='javascript:;' onclick='black_manager(this,"
												+ "\""
												+ data.uid
												+ "\","
												+ "\""
												+ data.isBlack
												+ "\")' class='ml-5' style='text-decoration:none'><i class='iconfont marginLeft12'>&#xe667;</i></a>";
										tr += "<a title='重置密码' href='javascript:;' onclick='user_change_pwd(this,"
												+ "\""
												+ data.uid
												+ "\")' class='ml-5' style='text-decoration:none'><i class='iconfont marginLeft12'>&#xe620;</i></a></td>";
										return tr;
									},
			"orderable" : false,
			"searchable" : false,
		} ]
		
	});
 
	$("#usersTable").find('tbody').addClass('tableTR');
	$("#searchUser").click(function() {
		$("#usersTable").dataTable().fnClearTable();
	});
});

function user_add_edit(title, url, w, h) {
	layer_show(title, url, w, h);
}

function user_del(obj, id) {
	var dataNum = parseInt($("#dataNum").html());
	layer.confirm('用户删除须谨慎，确认要删除吗？', function(index) {
		if (id != "") {
			$.ajax({
				url : rootPath + '/user/deleteUser?uid=' + id,
				type : 'GET',
				dataType : 'json',
				success : function(data) {
					if (data.returnCode == "0000") {
						$(obj).parents("tr").remove();
						layer.msg('已删除!', {
							icon : 1,
							time : 1000
						});
					} else {
						layer.alert(data.returnMessage);
					}
				},
				error : function(data) {
					//layer.alert("error:(");
					$("#refresh").click();
				},
			});
		}
	});
}

//清空用户缓存
function user_update_mts(obj, id) {
	if(id != "") {
		$.ajax({
			url : rootPath + '/user/flushUserCache?uid=' + id,
			type : 'GET',
			dataType : 'json',
			success : function(data) {
				if (data.returnCode == "0000") {
					layer.msg('清空成功!', {icon : 1,time : 1000});
				} else {
					layer.alert(data.returnMessage);
				}
			},
			error : function(data) {
				//layer.alert("清空用户缓存失败:(");
				$("#refresh").click();
			},
		});
	}
}

function user_change_pwd(obj, id) {
	layer.confirm('该操作将重置此用户密码为初始密码(000000)，确定要重置吗？', function(index) {
		if (id != "") {
			$.ajax({
				url : rootPath + '/user/changeUserPwd',
				type : 'POST',
				data : JSON.stringify({"uid":id}),
				contentType : 'application/json;charset=UTF-8',
				success : function(data) {
					if("0000" == data.returnCode) {						
						layer.msg('密码已重置', {
							icon : 1,
							time : 1000
						});
					} else {
	            		layer.alert(data.returnMessage);
	            	}
				},
				error : function(jqXHR, textStatus, errorThrown) {
//					layer.msg('error:)', {
//						icon : 1,
//						time : 1000
//					});
					$("#refresh").click();
				}
			});
		}
	});
}

function datadel() {
	var uids = new Array();
	$("input:checkbox[name='userCheckbox']:checked").each(function(k) {
		uids.push($(this).val());
	});
	var length = uids.length;
	var dataNum = parseInt($("#dataNum").html());
	if (length > 0) {
		layer.confirm('用户删除须谨慎，确认要删除吗？', function(index) {
			$.ajax({
				url : rootPath + '/user/deleteUsers',
				type : 'POST',
				traditional : true,
				data : JSON.stringify(uids),
				contentType : 'application/json;charset=UTF-8',
				dataType : "json",
				success : function(data) {
					if (data.returnCode == "0000") {
						$("input:checkbox:checked").each(function(k) {
							$(this).parents("tr[name='userTr']").remove();
						});
						layer.msg('已删除!', {
							icon : 1,
							time : 1000
							},
							function(){
								$("#usersTable").dataTable().fnClearTable();
						});
					} else {
						layer.alert(data.returnMessage);
					}
				},
				error : function(data) {
					//layer.alert("error:(");
					$("#refresh").click();
				},
			});
		});
	} else {
		layer.alert("请选择需要删除的用户!!!");
	}
}

function formatUndefined(value) {
	if(value == undefined) {
		value = "";
	}
	return value;
}

function black_manager(obj, id, isBlack) {
	layer.confirm(isBlack == '1'?'取消黑名单么？':'确定添加黑名单么？', function(index) {
		$.ajax({
			url : rootPath + '/user/changeBlackList',
			type : 'POST',
			contentType : 'application/json',
			data : JSON.stringify({
				//拉黑的就传原值 服务器做判断 相反
				"isBlack" : isBlack,
				"uid": id
			}),
			success : function(data) {
				if (data.returnCode == "0000") {
					
					if (isBlack == '1') {
						layer.msg('已恢复使用!', {
							icon : 1,
							time : 1000
						},
						function(){
							$("#usersTable").dataTable().fnClearTable();
						});
					} else {
						layer.msg('已禁用!', {
							icon : 1,
							time : 1000
						},
						function(){
							$("#usersTable").dataTable().fnClearTable();
						});
					}
				}else{
					layer.msg(data.returnMessage, {
						icon : 2,
						time : 2000
					});
				}
				
			},
			error : function(jqXHR, textStatus, errorThrown) {
				//layer.alert("error:(");
				$("#refresh").click();
			}	
		});
	});

}